<style scoped>
    .layout{
        border: 1px solid #d7dde4;
        background: #f5f7f9;
    }
    .layout-logo{
        width: 100px;
        height: 30px;
        background: #5b6270;
        border-radius: 3px;
        float: left;
        position: relative;
        top: 15px;
        left: 20px;
    }
    .layout-nav{
        width: 420px;
        margin: 0 auto;
    }
    .layout-assistant{
        width: 300px;
        margin: 0 auto;
        height: inherit;
    }
    .layout-breadcrumb{
        padding: 10px 15px 0;
    }
    .layout-content{
        min-height: 200px;
        margin: 15px;
        overflow: hidden;
        background: #fff;
        border-radius: 4px;
    }
    .layout-content-main{
        padding: 10px;
    }
    .layout-copy{
        text-align: center;
        padding: 10px 0 20px;
        color: #9ea7b4;
    }
    .tree{
        width:100px;
    }
    .searchInput{
        float:left;
        width:300px;
    }
    .ivu-modal{
        height:600px;
    }
</style>
<template>
    <div class="layout">
        <div class="layout-content">
            <Row>
                <Col span="5" class="tree">
                    <Tree :data="data5" @on-select-change="selectNode" ref="tree"></Tree>
                </Col>
                <Col span="19">
                    <div class="layout-content-main">
                        <Button type="primary" @click="onAdd">添加</Button>
                        <Button type="primary" @click='deletes'>删除</Button>
                        
                        <Input v-model="searchValue" class='searchInput'>
                            <Button type="primary" slot="append" icon="ios-search" @click="onSearch">搜索</Button>
                        </Input>
                        <Table border :columns="columns7" :data="data6" @on-selection-change="onSelectionChange"></Table>
                        <Page :total="pageCount" :page-size="pageSize" show-sizer show-elevator show-total 
                        @on-change="change" @on-page-size-change="changePage"></Page>
                        <Modal v-model="modal1" title="添加新闻">
                            <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="50">
                                <FormItem label="标题" prop="title">
                                    <Input type="text" v-model="formValidate.title"></Input>
                                </FormItem>
                                <FormItem label="编辑" prop="author">
                                    <Input type="text" v-model="formValidate.author"></Input>
                                </FormItem>
                                <FormItem label="内容" prop="content">
                                    <vue-editor v-model="formValidate.content" class="editor"></vue-editor>
                                </FormItem>
                                <FormItem label="图片" prop="image">
                                    <img :src="src" style="width:100px;height:100px;"></img>
                                    <Button type="primary" @click="showImage">显示对话框</Button>  
                                </FormItem>
                                <FormItem>
                                    <Button type="primary" @click="handleSubmit('formValidate')">提交</Button>
                                    <Button type="ghost" @click="handleReset('formValidate')" style="margin-left: 8px">重置</Button>
                                </FormItem>
                            </Form>
                        </Modal>
                    </div>
                </Col>
            </Row>
        </div>
        
        <div class="layout-copy">
            2011-2016 &copy; TalkingData
        </div>
        <Modal
            v-model="modal2"
            title="请选择图片"
            width="1000"
           >
            <app-upload v-if="showUpload" @imgObject="getImg"></app-upload>
        </Modal>
    </div>
</template>
<script>
    import { VueEditor } from 'vue2-editor';
    import {msgLine} from "../../main.js";
    import upload from "../upload/upload.vue";
    import {formatDate} from '../../date.js';
    export default {
        components: {
            VueEditor,
            appUpload:upload,
        },
        data () {
            return {
                time:'2017-11-01T01:42:16.930Z',
                src:'',
                pageCount:0,
                pageSize:10,
                history:[],
                ids:[],
                imgObject:{},
                searchValue:'',
                modal1: false,
                showUpload:false,
                modal2:false,
                showUpload:false,
                formValidate: {
                   title:'',
                   author:'',
                   content:'123',
                   categoryId:'',
                   image:'',
                },
                ruleValidate: {
                    title: [
                        { required: true, message: '标题不能为空', trigger: 'blur' }
                    ],
                    author: [
                        { required: true, message: '编辑不能为空', trigger: 'blur' },
                    ],
                    content: [
                        { required: true, message: '内容不能为空', trigger: 'blur' },
                    ],
                },
                columns7: [
                    {
                        type: 'selection',
                        width:60,
                        align: 'center'
                    },
                    {
                        type: 'index',
                        title:'序号',
                        width:65,
                        align: 'center'
                    },
                    {
                        title: '标题',
                        key: 'title',
                        align: 'center'
                    },
                    {
                        title: '编辑',
                        key: 'author',
                        width:80,
                        align: 'center'
                    },
                    {
                        title: '发布时间',
                        width:140,
                        key: 'releaseTime',
                        align: 'center',
                    },
                    {
                        title: '评论数',
                        key: 'commentCount',
                        width:90,
                        align: 'center'
                    },
                    {
                        title: '操作',
                        key: 'action',
                        width: 220,
                        align: 'center',
                        render: (h, params) => {
                            return h('div', [
                                h('Button', {
                                    props: {
                                        type: 'primary',
                                        size: 'small'
                                    },
                                    style: {
                                        marginRight: '5px'
                                    },
                                    on: {
                                        click: () => {
                                            this.show(params.row)
                                        }
                                    }
                                }, '查看'),
                                h('Button', {
                                    props: {
                                        size: 'small',
                                        type:'warning'
                                    },
                                    style: {
                                        marginRight: '5px'
                                    },
                                    on: {
                                        click: () => {
                                            this.onUpdate(params.row);
                                        }
                                    }
                                }, '修改'),
                                h('Button', {
                                    props: {
                                        size: 'small',
                                        type:'success'
                                    },
                                    style: {
                                        marginRight: '5px'
                                    },
                                    on: {
                                        click: () => {
                                             this.$router.replace({ path: '/comment/'+params.row._id});
                                        }
                                    }
                                }, '评论'),
                                h('Button', {
                                    props: {
                                        size: 'small',
                                        type:'error'
                                    },
                                    on: {
                                        click: () => {
                                            this.confirm(params.index)
                                        }
                                    }
                                }, '删除')
                            ]);
                        }
                    }
                ],
                data6: [],
                data5: [
                    {
                        title: '分类',
                        expand: true,
                        render: (h, { root, node, data }) => {
                            return h('span', {
                                style: {
                                    display: 'inline-block',
                                    width: '100%'
                                }
                            }, [
                                h('span', [
                                    h('Icon', {
                                        props: {
                                            type: 'ios-folder-outline'
                                        },
                                        style: {
                                            marginRight: '8px'
                                        }
                                    }),
                                    h('span', data.title)
                                ]),
                                h('span', {
                                    style: {
                                        display: 'inline-block',
                                        float: 'right',
                                        marginRight: '32px'
                                    }
                                }, [
                                    h('Button', {
                                        props: Object.assign({}, this.buttonProps, {
                                            icon: 'ios-plus-empty',
                                            type: 'primary'
                                        }),
                                        style: {
                                            width: '52px'
                                        },
                                        on: {
                                            click: () => { this.append(data) }
                                        }
                                    })
                                ])
                            ]);
                        },
                        children: [],
                    }
                ],
                buttonProps: {
                    type: 'ghost',
                    size: 'small',
                }
            }
        },
        methods: {
            formatDate(time) {
                var date = new Date(time);
                return formatDate(date, 'yyyy-MM-dd hh:mm');
            },
            dateFormat(){
                return 1;
            },
            getImg(res){
                this.imgObject=res[0];
                this.src="http://localhost:3000/"+res[0].filename;
            },
            show (row) {
                this.$Modal.info({
                    title:'新闻信息',
                    content:`ID：${row._id}<br/>
                    标题：${row.title}<br/>
                    类型：${row.categoryId}<br/>
                    编辑：${row.author}<br/>
                    发布时间:${row.releaseTime}</br/>
                    内容：${row.content}`
                })
            },
            confirm (index) {
                this.$Modal.confirm({
                    title: '警告！',
                    content: '<p>你确定要删除该新闻吗</p>',
                    onOk: () => {
                        var deleteUrl='http://localhost:3000/news/data/'+this.data6[index]._id;
                        this.$http.delete(deleteUrl)
                        .then(res=>{
                            this.getNews();
                        })
                    }
                });
            },
            change(index){
                var _start = ( index - 1 ) * this.pageSize;
                var _end = index * this.pageSize;
                this.data6 = this.history.slice(_start,_end);
            },
            changePage(q){
                this.pageSize=q;
                 this.data6 = this.history.slice(0,this.pageSize);
            },
            onUpdate(row){
                this.modal1=true;
                Object.assign(this.$data.formValidate,row);
            },
            onSearch(){
                this.getNews();
            },
            onAdd(){
                this.$data.formValidate={};
                var len=this.getSelectedNodes().length;
                if(len>0){
                    this.modal1=true;
                }else{
                     this.$Modal.error({
                        title: "提示",
                        content: "请先选择左侧新闻类型",
                    });
                }
            },
            showImage(){
                this.modal2=true;
                this.showUpload=true;
            },
            handleSubmit (name) {
                this.$refs[name].validate((valid) => {
                    if (valid) {
                        var treeNode=this.getSelectedNodes();
                        this.formValidate.categoryId=treeNode[0]._id;
                        this.formValidate.img=this.imgObject;
                        if(this.formValidate._id&&this.formValidate._id.length>0){
                             this.$http.put(`http://localhost:3000/news/data/${this.formValidate._id}`,this.formValidate)
                            .then(res=>{
                                this.$Message.success('修改成功!');
                                this.modal1=false;
                                this.getNews();
                            })
                        }else{
                            // console.log(this.formValidate);
                            this.$http.post('http://localhost:3000/news/data',this.formValidate)
                            .then(res=>{
                                this.$Message.success('提交成功!');
                                this.modal1=false;
                                this.getNews();
                            })
                        }
                    } else {
                        this.$Message.error('表单验证失败!');
                    }
                })


            },
            handleReset (name) {
                this.$refs[name].resetFields();
            },
            getSelectedNodes(){
                return this.$refs.tree.getSelectedNodes();
            },
            onSelectionChange(selection){
                if(selection&&selection.length>0){
                    var ids=[];
                    let len=selection.length;
                    for(let i=0;i<len;i++){
                        ids.push(selection[i]._id);
                    }
                    this.ids=ids;
                }
            },
            deletes(){
                if(this.ids.length>0){
                    this.$Modal.confirm({
                        title: '警告！',
                        content: '<p>你确定要删除该用户吗</p>',
                        onOk: () => {
                            this.$http.post('http://localhost:3000/news/deletes',{idarr:this.ids.toString()})
                            .then(res=>{
                                this.$Message.info("删除数据成功");
                                this.getNews();
                            })
                        }
                    });
                }else{
                    this.$Modal.warning({title: "警告！",content:"请选择要删除的数据!"});
                }
            },
            selectNode(res){
                var resLen=res.length;
                if(resLen>0){
                    this.$http.get('http://localhost:3000/classify/allnode/'+res[0]._id)
                    .then(res=>{
                        var dataChildren=res.data.toString();
                        this.$http.post('http://localhost:3000/news/children',{categoryId:dataChildren})
                        .then(res=>{
                            this.pageCount=res.data.length;
                            this.history=res.data;
                            this.data6 = this.history.slice(0,10);
                             for(var i=0;i<res.data.length;i++){
                                res.data[i].releaseTime=this.formatDate(res.data[i].releaseTime);
                            }
                        })  
                    })
                }else{
                    this. getNews();
                }
            },
            getClassifyData(){
                this.$http.get('http://localhost:3000/classify/list/1')
                .then(res=>{
                    this.data5=res.data;
                })
            },
            getNews(){
                this.$http.post('http://localhost:3000/news/list',{title:this.searchValue})
                .then(res=>{
                    this.pageCount=res.data.rows.length;
                    this.history=res.data.rows;
                    this.data6 = this.history.slice(0,10);
                    for(var i=0;i<res.data.rows.length;i++){
                        res.data.rows[i].releaseTime=this.formatDate(res.data.rows[i].releaseTime);
                    }
                })
            }
        },
        created(){
            this.getClassifyData();
            this.getNews();
        }
    }
</script>